<style lang="less">
    @import "bankArriveManagement.less";
</style>
<template>
    <div>
        <Card>
            <Row>
                <Form ref="searchForm" :model="searchForm" inline :label-width="90" class="search-form">
                    <div class="search">
                        <Row>
                            <Col align="left">
                                <Form-item label="网银编号" prop="ebankNo">
                                    <Input type="text" v-model="searchForm.ebankNo" clearable placeholder="请输入网银编号"/>
                                </Form-item>
                                <Form-item label="付款客户" prop="custName">
                                    <Input type="text" v-model="searchForm.custName" clearable placeholder="请输入付款客户姓名"/>
                                </Form-item>
                                <Form-item label="到账银行" prop="arriveBank">
                                    <Select v-model="searchForm.arriveBank" clearable placeholder="请选择到账银行">
                                        <Option v-for="item in backAccount" :value="item.account"
                                                :label="setDictTitleByType('bankCode',item.bankCode)+':'+item.account"
                                                :key="item.account">
                                            {{ setDictTitleByType('bankCode',item.bankCode)+':'+item.account }}
                                        </Option>
                                    </Select>
                                </Form-item>
                                <Form-item label="状态" prop="status">
                                    <Select v-model="searchForm.status" clearable placeholder="请选择到账记录状态">
                                        <Option v-for="item in dataDic.AccountRegistStatus" :value="item.value"
                                                :label="item.title" :key="item.value">{{ item.title }}
                                        </Option>
                                    </Select>
                                </Form-item>
                                <Form-item label="到账时间">
                                    <DatePicker v-model="selectDate" type="daterange" :start-date="dateFocus" format="yyyy-MM-dd" clearable
                                                @on-change="selectDateRange" placeholder="请选择到账时间">
                                    </DatePicker>
                                </Form-item>
                            </Col>
                        </Row>
                        <Row>
                            <Col align="middle">
                                <Form-item>
                                    <Button @click="handleSearch" type="primary" icon="ios-search">搜索</Button>
                                    <Button @click="handleReset" type="primary" icon="ios-trash">重置</Button>
                                </Form-item>
                            </Col>
                        </Row>
                        <Row class="operation">
                            <Button @click="addRegister" type="primary" icon="md-add">新增</Button>
                            <Button @click="openImportView" type="primary" icon="md-copy">导入</Button>
                            <Button @click="generaRegisterMulit" type="primary" icon="ios-send">批量生成凭证</Button>
                        </Row>
                    </div>
                    <Row>
                        <Alert show-icon>
                            已选择 <span class="select-count">{{selectCount}}</span> 项
                            <a class="select-clear" @click="clearSelectAll">清空</a>
                        </Alert>
                    </Row>
                    <Row>
                        <Table :loading="loading" border :columns="columns" :data="data" sortable="custom"
                               @on-selection-change="showSelect" ref="table">
                            <template slot-scope="{ row, index }" slot="id">
                                <Button v-show="row.status == 'NOT_GENERA'"
                                        type="primary" size="small" @click="editRegister(row)">编辑
                                </Button>
                                <Button v-show="row.status == 'NOT_GENERA'"
                                        type="error" size="small" @click="deleteRegister(row)">删除
                                </Button>
                                <Button v-show="row.status == 'NOT_GENERA'"
                                        type="error" size="small" @click="generaRegister(row)">生成凭证
                                </Button>
                                <Button v-show="row.status == 'ALREADY_GENERA'"
                                        type="error" size="small" @click="writeBack(row)">红冲
                                </Button>
                            </template>
                            <template slot-scope="{ row, index }" slot="status">
                                <span>{{setDictTitleByType("AccountRegistStatus",row.status)}}</span>
                            </template>
                            <template slot-scope="{ row, index }" slot="receivingBank">
                                <span>{{setDictTitleByType("bankCode",row.receivingBank)}}</span>
                            </template>
                            <template slot-scope="{ row, index }" slot="receivedAmt">
                                <span>{{row.receivedAmt==""?"":row.receivedAmt.toFixed(2)}}</span>
                            </template>
                        </Table>
                    </Row>
                    <Row type="flex" justify="end" class="page">
                        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize"
                              @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]"
                              size="small" show-total show-elevator show-sizer></Page>
                    </Row>
                </Form>
            </Row>
        </Card>
        <Modal
            :title="modalTitle"
            v-model="modalVisible"
            :mask-closable="false"
            :width="500"
            :styles="{top: '90px'}"
        >
            <Form ref="form" :model="form" :label-width="100" :rules="formValidate" class="modalClass">

                <FormItem label="网银编号" prop="ebankNo">
                    <Input v-model="form.ebankNo" placeholder="请输入网银编号"/>
                </FormItem>
                <FormItem label="到账时间" prop="arrivalTime">
                    <DatePicker v-model="form.arrivalTime" :options="dateLimit" :start-date="dateFocus" placeholder="请选择到账时间" format="yyyy-MM-dd"></DatePicker>
                </FormItem>
                <FormItem label="业务日期" prop="businessTime">
                    <DatePicker v-model="form.businessTime" disabled  placeholder="" format="yyyy-MM-dd"></DatePicker>
                </FormItem>
                <Form-item label="到账银行" prop="bank">
                    <Select v-model="form.bank" clearable placeholder="请选择到账银行"
                            @on-change="selectBankAccount(form.bank)">
                        <Option v-for="item in backAccount" :value="item.account"
                                :label="setDictTitleByType('bankCode',item.bankCode)+':'+item.account"
                                :key="item.account">
                            {{ setDictTitleByType('bankCode',item.bankCode)+':'+item.account }}
                        </Option>
                    </Select>
                </Form-item>
                <FormItem label="到账账号" prop="bankAccount">
                    <Input v-model="form.bankAccount" placeholder="请输入到账账号" @on-blur="inputBankAccount(form.bankAccount)"/>
                </FormItem>
                <FormItem label="到账金额" prop="receivedAmt">
                    <Input v-model="form.receivedAmt" placeholder="请输入到账金额"/>
                </FormItem>
                <FormItem label="付款客户" prop="paymentCust">
                    <Input v-model="form.paymentCust" placeholder="请输入付款客户姓名" />
                </FormItem>
                <FormItem label="客户账号" prop="custAccount">
                    <Input :maxlength="32" v-model="form.custAccount" placeholder="请输入客户账号" />
                </FormItem>
                <FormItem label="摘要" prop="summary">
                    <Input v-model="form.summary" placeholder="请输入摘要" />
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="modalVisible=false">取消</Button>
                <Button type="primary" :loading="submitLoading" @click="handelSubmit">提交</Button>
            </div>
        </Modal>
        <Modal
            title="银行到账记录导入"
            v-model="importModalVisible"
            :mask-closable="false"
            :closable="false"
            :width="800"
            :styles="{top: '90px'}"
        >
            <LeaseFileUpload :modal="false" v-if="initParam"
                             :requestPath="requestPath"
                             :chunkEnable="false"
                             @uploadFailed="uploadFailed" @afterUpload="messageUpload" @deleteFile="deleteFile" ref="uploaderModel">

            </LeaseFileUpload>
            <div slot="footer">
                <a href="/excel/网银到账记录导入模板.xlsx" download="网银到账记录导入模板.xlsx">模板下载</a>
                <Button type="text" @click="closeImportView">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

    import {getByTypes} from "_p/basic/api/admin/datadic";

    import {queryBankList} from "@/projects/basic/api/contract/bank-arrive/bankManagement";
    import {
        addSubmit,
        deleteAccountRegister,
        editSubmit,
        generaAccountRegister,
        queryBankArriveList,
        writeBack
    } from "@/projects/basic/api/contract/bank-arrive/bankArriveManagement";
    import {isTwoDicmal} from "@/projects/basic/assets/contract/js/utils";
    import LeaseFileUpload from '_c/file-upload/index'
    import config from '@/config/index'
    import {getSysTime} from "_p/basic/api/system-date";
    import moment from "moment";

    export default {
        name: "bank-arrive-management",
        components: {
            LeaseFileUpload
        },
        computed:{
        },
        data() {
            const validateAccount = (rule, value, callback) => {
                if (!this.backAccount) {
                    callback(new Error("系统中不存在银行账号，请维护公司银行账号"));
                } else {
                    let flag = false;
                    this.backAccount.forEach(column => {
                        if (column.account === value) {
                            flag = true;
                        }
                    });
                    if (!flag) {
                        this.form.bank = "";
                        callback(new Error("系统中不存在该银行账号，请检查输入是否争取或维护公司银行账号"));
                    } else {
                        callback();
                    }
                }
            };
            const isMoneyValue = (rule, value, callback) => {
                if (value) {
                    if (!isTwoDicmal(value) && value !== '') {
                        callback(new Error("请输入正确金额"))
                    } else {
                        if (value < 0) {
                            callback(new Error("金额必须大于0"))
                        } else {
                            callback()
                        }
                    }
                } else {
                    callback(new Error("不能为空"))
                }
            };
            return {
                dateLimit:{
                    disabledDate (date) {
                        return date && date.valueOf() > Date.now();
                    }
                },
                dateFocus: new Date(),
                modalTitle: "",
                modalVisible: false,
                modalType: "",
                submitLoading: false, // 添加或编辑提交状态
                batchDate:"",
                requestPath: config.getBaseUrl()+"/contractManage/bankArriveManagement/importRegister?batchDate=",
                form: {
                    ebankNo: "",
                    arrivalTime: "",
                    businessTime: "",
                    bank: "",
                    bankAccount: "",
                    receivedAmt: "",
                    paymentCust: "",
                    custAccount: "",
                    summary: "",
                    receivingBank: ""
                },
                formValidate: {
                    // 表单验证规则
                    ebankNo: [{required: true, message: "不能为空", trigger: "blur"}],
                    arrivalTime: [{required: true, message: "不能为空", type: "date", trigger: "blur"}],
                    bank: [{required: true, message: "不能为空", trigger: "change"}],
                    bankAccount: [
                        {required: true, message: "不能为空", trigger: "blur"},
                        {validator: validateAccount, trigger: "blur"}
                    ],
                    receivedAmt: [
                        {required: true, message: "不能为空", trigger: "blur"},
                        {validator: isMoneyValue, trigger: "blur"}
                    ],
                    paymentCust: [{required: true, message: "不能为空", trigger: "blur"}],
                    custAccount: [{required: true, message: "不能为空", trigger: "blur"}]
                },
                importModalVisible: false,
                initParam:false,
                searchForm: {
                    ebankNo: "",
                    startDate: "",
                    endDate: "",
                    arriveBank: "",
                    custName: "",
                    status: "ALREADY_GENERA",
                },
                data: [],
                backAccount: [],
                total: 0,
                selectDate: null,
                dicKeys: [
                    "AccountRegistStatus", "bankCode"
                ],
                dataDic: {},
                loading: false,
                columns: [
                    {type: "selection", minWidth: 60, maxWidth: 60, align: "center", fixed: "left",},
                    {title: "操作", key: "id", minWidth: 200, align: "center", slot: "id", fixed: "left"},
                    {title: "网银编号", key: "ebankNo", minWidth: 160, align: "center"},
                    {title: "到账时间", key: "arrivalTime", minWidth: 150, align: "center"},
                    {title: "业务时间", key: "businessTime", minWidth: 150, align: "center"},
                    {title: "到账银行", key: "receivingBank", minWidth: 150, align: "center", slot: "receivingBank"},
                    {title: "到账银行账户", key: "bankAccount", minWidth: 150, align: "center"},
                    {title: "付款客户", key: "paymentCust", minWidth: 150, align: "center"},
                    {title: "客户账号", key: "custAccount", minWidth: 150, align: "center"},
                    {title: "到账金额", key: "receivedAmt",  slot: "receivedAmt", minWidth: 150, align: "center"},
                    {title: "摘要", key: "summary", minWidth: 150, align: "center"},
                    {title: "状态", key: "status", minWidth: 150, align: "center", slot: "status"}
                ],
                selectCount: 0,
            }
        },
        methods: {
            closeImportView() {
                this.$refs.uploaderModel.cancelFiles();
                this.initParam = false;
                this.importModalVisible = false;
                this.getBankArriveList();
            },
            openImportView() {
                getSysTime().then(res => {
                    if (res.code === "0000" && res.data) {
                        this.batchDate = moment(res.data.bhDate).format('YYYY-MM-DD');
                        this.requestPath = this.requestPath + this.batchDate;
                        this.initParam = true;
                        this.importModalVisible = true;
                    }else{
                        this.$Message.error("系统时间获取失败，请重试");
                    }
                });
            },
            inputBankAccount(bankAccount) {
                this.backAccount.forEach(column => {
                    if (column.account === bankAccount) {
                        this.form.receivingBank = column.bankCode;
                        this.form.bank = column.account
                    }
                });
            },
            selectBankAccount(bank) {
                this.backAccount.forEach(column => {
                    if (column.account === bank) {
                        this.form.receivingBank = column.bankCode;
                        this.form.bankAccount = column.account;
                    }
                });
            },
            clearSelectAll() {
                this.$refs.table.selectAll(false);
            },
            deleteRegister(v) {
                let params = {
                    id: v.id
                }
                deleteAccountRegister(params).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.data);
                        this.getBankArriveList();
                    }
                });
            },
            editRegister(v) {
                getSysTime().then(res => {
                    if (res.code === "0000" && res.data) {
                        this.batchDate = moment(res.data.bhDate).format('YYYY-MM-DD');
                        this.modalType = 1;
                        this.$refs.form.resetFields();
                        // 转换null为""
                        for (let attr in v) {
                            if (v[attr] === null) {
                                v[attr] = "";
                            }
                        }
                        let str = JSON.stringify(v);
                        let data = JSON.parse(str);
                        this.form = data;
                        this.form.bank = this.form.bankAccount;
                        this.form.businessTime = this.batchDate;
                        this.modalTitle = "网银到账记录编辑";
                        this.modalVisible = true;
                    }else{
                        this.$Message.error("系统时间获取失败，请重试");
                    }
                });
            },
            addRegister(v) {
                getSysTime().then(res => {
                    if (res.code === "0000" && res.data) {
                        this.batchDate = moment(res.data.bhDate).format('YYYY-MM-DD');
                        this.modalType = 0;
                        this.$refs.form.resetFields();
                        this.form.businessTime = this.batchDate;
                        this.modalTitle = "新增网银到账记录";
                        this.modalVisible = true;
                    }else{
                        this.$Message.error("系统时间获取失败，请重试")
                    }
                });
            },
            handelSubmit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.submitLoading = true;
                        if (this.modalType === 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.form.id;
                            addSubmit(this.form).then(res => {
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getBankArriveList();
                                    this.modalVisible = false;
                                }
                            });
                        } else if (this.modalType === 1) {
                            // 编辑
                            editSubmit(this.form).then(res => {
                                if (res.code === "0000") {
                                    this.$Message.success("操作成功");
                                    this.getBankArriveList();
                                    this.modalVisible = false;
                                }
                            });
                        }
                        this.submitLoading = false;
                    }
                });
            },
            generaRegister(v) {
                let params = {
                    ids: v.id
                }
                generaAccountRegister(params).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.data);
                        this.getBankArriveList();
                    }
                });
            },
            generaRegisterMulit() {
                if (this.selectCount <= 0 || this.selectCount == undefined) {
                    this.$Message.warning("请勾选数据");
                    return;
                }
                let ldStr = "";
                let flag = true;
                this.selectList.forEach(function (e) {
                    if (e.status == "NOT_GENERA") {
                        ldStr += e.id + ",";
                    } else {
                        flag = false;
                    }
                });
                if (!flag) {
                    this.$Message.warning("只有状态为未生成凭证的到账记录可以生成凭证，请检查勾选数据");
                    return;
                }
                let params = {
                    ids: ldStr
                }
                generaAccountRegister(params).then(res => {
                    if (res.code === "0000") {
                        this.$Message.success(res.data);
                        this.getBankArriveList();
                    }
                });
            },
            writeBack(v) {
                this.$Modal.confirm({
                    title: "红冲凭证",
                    content: "您确认要红冲凭证?",
                    onOk: () => {
                        this.operationLoading = true;
                        let params = {
                            ids: v.id
                        }
                        writeBack(params).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success(res.data);
                                this.getBankArriveList();
                            }
                        }).catch(() => {
                            this.operationLoading = false;
                        });
                    }
                });
            },
            handleSearch() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getBankArriveList();
            },
            handleReset() {
                this.$refs.searchForm.resetFields();
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.selectDate = null;
                this.searchForm.startDate = "";
                this.searchForm.endDate = "";

                // 重新加载数据
                this.getBankArriveList();
            },
            selectDateRange(v) {
                if (v) {
                    this.searchForm.startDate = v[0];
                    this.searchForm.endDate = v[1];
                }
            },
            changePage(v) {
                this.searchForm.pageNumber = v;
                this.getBankArriveList();
            },
            changePageSize(v) {
                this.searchForm.pageSize = v;
                this.getBankArriveList();
            },
            initDataDic() {
                let self = this;
                getByTypes(this.dicKeys).then(res => {
                    if (res.code === "0000" && res.data) {
                        self.dataDic = res.data;
                    }
                });
            },
            getDic(v) {
                let dic = []
                switch (v) {
                    case "AccountRegistStatus":
                        dic = this.dataDic.AccountRegistStatus;
                        break;
                    case "bankCode":
                        dic = this.dataDic.bankCode;
                        break;
                    default:
                }
                return dic;
            },
            setDictTitleByType(v1, v2) {
                let dic = {}
                if (!this.getDic(v1)) return '';
                this.getDic(v1).forEach(column => {
                    if (column.value === v2) {
                        dic = column;
                    }
                });
                return dic.title;
            },
            showSelect(e) {
                this.selectList = e;
                this.selectCount = e.length;
            },
            getBankArriveList() {
                // 多条件搜索任务列表
                this.loading = true;
                queryBankArriveList(this.searchForm).then(res => {
                    this.loading = false;
                    if (res.code === "0000") {
                        this.data = res.data.records;
                        this.total = res.data.total;
                    }
                });
                this.selectCount = 0;
            },
            initBankAccount() {
                let params = {
                    //确认是否需要限定为有效状态的对公账号
                    status: "valid",
                    pageNumber: 1,
                    pageSize: 1000
                };
                queryBankList(params).then(res => {
                    if (res.code === "0000") {
                        this.backAccount = res.data.records;
                    }
                });
            },
            init() {
                this.searchForm.pageNumber = 1;
                this.searchForm.pageSize = 10;
                this.getBankArriveList();
            },
            messageUpload(uploadInfo) {
                this.$Message.info("导入成功");
            },
            uploadFailed(uploadInfo) {
                this.$Message.error({
                    content:uploadInfo[0].msg,
                    duration:10
                });
            },
            deleteFile(fileInfo) {
            }
        },
        mounted() {
            this.initBankAccount();
            this.initDataDic();
            this.init();
        }
    }
</script>

<style scoped>

</style>
